package com.platform.api;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.platform.entity.AddressEntity;
import com.platform.entity.OrderEntity;
import com.platform.entity.UserEntity;
import com.platform.service.AddressService;
import com.platform.service.OrderService;
import com.platform.util.ApiBaseAction;
import com.platform.utils.R;

import io.swagger.annotations.Api;

@Api(tags = "API订单相关接口")
@RestController
@RequestMapping("/api/order")
public class ApiOrderController extends ApiBaseAction{
    @Autowired
    private OrderService orderService;
    @Autowired
    private AddressService addressService;

    @RequestMapping("/newfromproduct/{productId}/{productNum}")
    public R newFromProduct(@PathVariable("productId") Integer productId, 
    		@PathVariable("productNum") Integer productNum) {
        try {
        	UserEntity user = getCurrentUser();
        	Map<String,Object> params = new HashMap<String,Object>();
        	params.put("userId", user.getId());
        	List<AddressEntity> addresses = addressService.queryList(params);
        	AddressEntity defaultAddress = null;
        	if(addresses.size() > 0) {
        		defaultAddress = addresses.get(0);
          		for(AddressEntity address:addresses) {
          			if(address.getIsdefault() == 1) {
          				defaultAddress = address;
            			break;
          			}
          		}
        	}
        	OrderEntity order = orderService.newSaveByProduct(user,defaultAddress,productId,productNum);
            return R.ok().put("orderId", order.getId());
        } catch (Exception e) {
        	logger.error("商品直购ERROR:"+e.getMessage(),e);
        	return R.error(e.getMessage());
        }
    }
    
    @RequestMapping("/changeaddress/{id}/{addressId}")
    public R changeAddress(@PathVariable("id") Integer id,@PathVariable("addressId") Integer addressId) {
        try {
        	UserEntity user = getCurrentUser();
        	OrderEntity order = orderService.changeAddress(id,addressId);
        	if(!order.getUserId().equals(user.getId())) {
        		return R.error("非本人订单");
        	}
        	AddressEntity address = null;
        	if(order.getAddressId() != null) {
        		address = addressService.queryObject(addressId);
        	}
            return R.ok().put("order", order).put("address", address);
        } catch (Exception e) {
        	logger.error("订单info"+ id + ":" +e.getMessage(),e);
        	return R.error(e.getMessage());
        }
    }
    
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Integer id) {
        try {
        	UserEntity user = getCurrentUser();
        	OrderEntity order = orderService.queryObject(id,true);
        	if(!order.getUserId().equals(user.getId())) {
        		return R.error("非本人订单");
        	}
        	AddressEntity address = null;
        	if(order.getAddressId() != null) {
        		address = addressService.queryObject(order.getAddressId());
        	}
            return R.ok().put("order", order).put("address", address);
        } catch (Exception e) {
        	logger.error("订单info"+ id + ":" +e.getMessage(),e);
        	return R.error(e.getMessage());
        }
    }
     
    @RequestMapping("/submit/{id}")
    public R submit(@PathVariable("id") Integer id) {
        try {
        	UserEntity user = getCurrentUser();
        	OrderEntity order = orderService.queryObject(id,true);
        	if(!order.getUserId().equals(user.getId())) {
        		return R.error("非本人订单");
        	}
        	AddressEntity address = null;
        	if(order.getAddressId() != null) {
        		address = addressService.queryObject(order.getAddressId());
        	}
            return R.ok().put("order", order).put("address", address);
        } catch (Exception e) {
        	logger.error("订单info"+ id + ":" +e.getMessage(),e);
        	return R.error(e.getMessage());
        }
    }
    
    
    @RequestMapping("/list")
    public R list() {
        try {
        	List<OrderEntity> allOrders;
        	List<OrderEntity> needPayOrders;
        	List<OrderEntity> needReciveOrders;
        	List<OrderEntity> needAppraiseOrders;
        	List<OrderEntity> saledOrders;
        	
        	UserEntity user = getCurrentUser();
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("userId", user.getId());
    		Integer[] noStatus = {102};
        	params.put("noStatus", noStatus);		//删除的不需要取
            params.put("offset", 0);
            params.put("limit", 6);
        	allOrders = orderService.queryList(params,true);
        	params.remove("noStatus");
            //1xx 表示订单取消和删除等状态 0订单创建成功等待付款，　101订单已取消，　102订单已删除  103 订单支付失败
            //2xx 表示订单支付状态 200 付款中　201订单已付款，等待发货
            //3xx 表示订单物流相关状态　300订单已发货， 301用户确认收货 待评价
            //4xx 表示订单退换货相关的状态　401 没有发货，退款　402 已收货，退款退货
            //999 完成
        	Integer[] statuses = {0};
        	params.put("statuses", statuses);		
        	needPayOrders = orderService.queryList(params,true);
        	Integer[] statuses2 = {200,201,300};
        	params.put("statuses", statuses2);		
        	needReciveOrders = orderService.queryList(params,true);
        	Integer[] statuses3 = {301};
        	params.put("statuses", statuses3);		
        	needAppraiseOrders = orderService.queryList(params,true);
        	Integer[] statuses4 = {999,401,402};
        	params.put("statuses", statuses4);		
        	saledOrders = orderService.queryList(params,true);
            return R.ok().put("allOrders", allOrders).put("needPayOrders", needPayOrders)
            		.put("needReciveOrders", needReciveOrders).put("needAppraiseOrders", needAppraiseOrders)
            		.put("saledOrders", saledOrders);
        } catch (Exception e) {
        	logger.error("订单list:" +e.getMessage(),e);
        	return R.error(e.getMessage());
        }
    }
    
    @RequestMapping("/list/{state}")
    public R listStatus(@PathVariable("state") Integer state,
    		@RequestParam Map<String, Object> map) {
        try {
        	UserEntity user = getCurrentUser();
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("userId", user.getId());
        	switch(state) {
	        	case 0:
	        		Integer[] noStatus = {102};
	            	params.put("noStatus", noStatus);		
	            	break;
	        	case 1:
	            	Integer[] statuses = {0};
	            	params.put("statuses", statuses);		
	            	break;
	        	case 2:
	            	Integer[] statuses2 = {200,201,300,301};
	            	params.put("statuses", statuses2);		
	            	break;
	        	case 3:
	            	Integer[] statuses3 = {301};
	            	params.put("statuses", statuses3);	
	            	break;
	        	case 4:
	            	Integer[] statuses4 = {999,400,401,402,500,501,502};
	            	params.put("statuses", statuses4);	
	            	break;
	    		default:
	        		Integer[] noStatus5 = {102};
	            	params.put("noStatus", noStatus5);		
	    	}
            
            if(map.get("offset") != null) {
                params.put("offset", Integer.valueOf(map.get("offset").toString()));
            }else {
                params.put("offset", 0);
            }
            params.put("limit", 6);
            List<OrderEntity> orders = orderService.queryList(params,true);

            return R.ok().put("orders", orders);
        } catch (Exception e) {
        	logger.error("订单list:" +e.getMessage(),e);
        	return R.error(e.getMessage());
        }
    }
    
    @RequestMapping("/cancel/{orderId}")
    public R cancel(@PathVariable("orderId") Integer orderId,ModelMap map) {
        try {
        	Integer userId = getCurrentUserId();
        	int result = orderService.cancel(orderId,userId);
        	if(result <=0) {
        		return R.error("非本人订单或未付款订单，无法取消！");
        	}
            return R.ok();
        } catch (Exception e) {
        	logger.error("ApiOrderController cancel:", e);
        	return R.error("未知错误："+e.getMessage());
        }
    }

    @RequestMapping("/confirm/{orderId}")
    public R confirm(@PathVariable("orderId") Integer orderId) {
        try {
        	Integer userId = getCurrentUserId();
        	int result = orderService.confirm(orderId,userId);
        	if(result <=0) {
        		return R.error("非本人订单或非发货状态订单，无法确认收货！");
        	}
           return R.ok();
        } catch (Exception e) {
        	logger.error("MpOrderController confirm:", e);
        	return R.error("未知错误："+e.getMessage());
        }
    }
    
    /**
     * 前端反馈支付成功，实际需后台与第三方平台确认
     * @param orderId
     * @return
     */
    @RequestMapping("/paying/{orderId}")
    public R paying(@PathVariable("orderId") Integer orderId) {
        try {
        	Integer userId = getCurrentUserId();
        	int result = orderService.paying(orderId,userId);
        	if(result <=0) {
        		return R.error("非本人订单或非发货状态订单，无法确认收货！");
        	}
           return R.ok();
        } catch (Exception e) {
        	logger.error("MpOrderController confirm:", e);
        	return R.error("未知错误："+e.getMessage());
        }
    }
    
    @RequestMapping("/delete/{orderId}")
    public R deleteById(@PathVariable("orderId") Integer orderId) {
    	try {
    		Integer userId = getCurrentUserId();
    		int result = orderService.deleteById(orderId,userId);
    		if(result <=0) {
    			return R.error("非本人订单或订单非未付款状态！");
    		}
    		return R.ok();
    	} catch (Exception e) {
    		logger.error("MpOrderController confirm:", e);
    		return R.error("未知错误："+e.getMessage());
    	}
    }
}
